<template>
  <el-option ref="el" class="el-select-loading" value="">
    <template v-if="hasMore">
      <el-icon class="el-select-loading__icon"><Loading /></el-icon>
      <i></i>
      <span class="el-select-loading__tips">{{ loadingText }}</span>
    </template>
    <template v-else>{{ noMoreText || "到底了~" }}</template>
  </el-option>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from "vue";

const props = defineProps({
  hasMore: {
    required: true,
    type: Boolean,
  },
  page: {
    required: true,
    type: Number
  },
  loadingText: {
    default: '正在加载'
  },
  loading: {
    required: true,
    type: Boolean
  },
  noMoreText: {
    default: '到底了'
  }
});
const emits = defineEmits(['loadMore']);
const el = ref(null);
const observer = ref(null);

onMounted(() => {
  if (!el.value){
    return;
  }
  const callback = (entries) => {
    if (props.loading || !props.hasMore || !entries[0].isIntersecting){
      return;
    }
    emits('loadMore', props.page + 1);
  }
  const options = {
    root: el.value.$el.parentElement?.parentElement,
    rootMargin: '0px 0px 0px 0px'
  };
  observer.value = new IntersectionObserver(callback, options);
  observer.value.observe(el.value.$el);
})
onUnmounted(() => {
  if (!el.value) {
    return;
  }
  observer.value?.unobserve(el.value.$el);
});
</script>
<style lang='scss' scoped>
.el-select-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: initial;
  pointer-events: none;
  color: var(--el-color-info);
  font-size: 12px;

  &__icon {
    font-size: 16px;
    animation: rotate 1.5s linear infinite;
  }

  &__tips {
    margin-left: 6px;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
}
</style>